package richbar.com.richbar.view.pop;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.ListViewCompat;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.common.util.DisplayUtil;
import com.common.util.LogUtil;
import com.common.util.StringUtil;
import com.common.util.ToastUtil;
import com.okhttp.GlideUtil;
import com.okhttp.network.HttpUtils;
import com.okhttp.network.MyGson;

import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;
import richbar.com.richbar.R;
import richbar.com.richbar.base.BaseListAdapter;
import richbar.com.richbar.bean.GoodsInfoResult;
import richbar.com.richbar.bean.PriceResult;
import richbar.com.richbar.util.NetWorkUtil;
import richbar.com.richbar.view.NoScrollGridView;

/**
 * Created by QiYang on 2018/12/4.
 */

public class TypePop implements View.OnClickListener {
    private Activity context;
    private GoodsInfoResult.DataEntity.InfoEntity data;
    private Callback callback;
    private List<String> ids;
    private List<String> values;
    private String goodsPrice;
    TextView price;
    TextView pricePoint;
    TextView num ;
    private ProgressBar progressBar;
    private int goodsNum = 1;
    PopupWindow popupWindow;
    String pic;

    public TypePop(Activity context,String pic, GoodsInfoResult.DataEntity.InfoEntity data) {
        this.context = context;
        this.data = data;
        this.pic = pic;
        LogUtil.e("PPAPAPAPDDD",pic);
        ids = new ArrayList<>();
        values = new ArrayList<>();
    }

    public void show(Callback callback) {
        this.callback = callback;
        //准备PopupWindow的布局View
        View view = LayoutInflater.from(context).inflate(R.layout.pop_type, null);
        ImageView close = view.findViewById(R.id.close);

        ImageView iv = view.findViewById(R.id.iv);
        TextView rebate = view.findViewById(R.id.rebate);
        TextView rebatePoint = view.findViewById(R.id.rebate_point);
        price = view.findViewById(R.id.price);
        pricePoint = view.findViewById(R.id.price_point);
        TextView stockNum = view.findViewById(R.id.stock_num);
        num = view.findViewById(R.id.num);
        ListView listView = view.findViewById(R.id.listView);

        progressBar = view.findViewById(R.id.progressBar);

        view.findViewById(R.id.add).setOnClickListener(this);
        view.findViewById(R.id.delete).setOnClickListener(this);
        view.findViewById(R.id.add_car).setOnClickListener(this);
        view.findViewById(R.id.buy).setOnClickListener(this);

        if (null != data && null != data.getAttr() && data.getAttr().size() > 0) {

            MyAdapter adapter = new MyAdapter(context,data.getAttr());
            listView.setAdapter(adapter);

            for (int i = 0; i < data.getAttr().size(); i++) {
                ids.add(data.getAttr().get(i).getValue().get(0).getId() + "");
                values.add(data.getAttr().get(i).getValue().get(0).getName());
            }

        }

        GlideUtil.loadImage(context, NetWorkUtil.URL + pic, iv);
        goodsPrice = data.getGoods_price();
        if (!StringUtil.isEmpty(goodsPrice)) {
            price.setText(goodsPrice.substring(0, goodsPrice.indexOf(".")));
            pricePoint.setText(goodsPrice.substring(goodsPrice.indexOf("."), goodsPrice.length()));
        }
        String goodsRebate = data.getGoods_rebate();
        if (!StringUtil.isEmpty(goodsRebate)) {
            rebate.setText(goodsRebate.substring(0, goodsRebate.indexOf(".")));
            rebatePoint.setText(goodsRebate.substring(goodsRebate.indexOf("."), goodsRebate.length()));
        }

        popupWindow = new PopupWindow(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setContentView(view);
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setOutsideTouchable(false);
        popupWindow.setClippingEnabled(false);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (context != null) {
                    setBackgroundAlpha(context, 1.0f);
                }
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        if (null != popupWindow && !popupWindow.isShowing()) {
            popupWindow.showAtLocation(context.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        }
        setBackgroundAlpha(context, 0.5f);//设置屏幕透明度
    }


    private void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        if (bgAlpha == 1.0f) {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        activity.getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add:
                goodsNum ++;
                num.setText(goodsNum + "");
                break;
            case R.id.delete:
                if (goodsNum > 1) {
                    goodsNum --;
                    num.setText(goodsNum + "");
                }
                break;
            case R.id.add_car:
                addCar();
                break;
            case R.id.buy:
                buy();
                break;
        }
    }

    private void buy() {
        callback.onBuy(StringUtil.listToStr(ids),StringUtil.listToStr(values),goodsPrice + "",goodsNum+"");
        popupWindow.dismiss();
    }

    private void addCar() {
        callback.onAdd(StringUtil.listToStr(ids),StringUtil.listToStr(values),goodsPrice + "",goodsNum+"");
        popupWindow.dismiss();
    }



   class MyAdapter extends BaseListAdapter<GoodsInfoResult.DataEntity.InfoEntity.AttrEntity> {
       public MyAdapter(Context context, List<GoodsInfoResult.DataEntity.InfoEntity.AttrEntity> data) {
           super(context, data);
       }

       @Override
       public View convert(int i, View view, ViewGroup viewGroup, GoodsInfoResult.DataEntity.InfoEntity.AttrEntity bean) {
           View v = inflater.inflate(R.layout.item_size_group,null);
           NoScrollGridView gridView = v.findViewById(R.id.gridView);
           TextView title = v.findViewById(R.id.title);
           title.setText(bean.getName());
           GridAdapter adapter = new GridAdapter(context,bean.getValue(),i);
           gridView.setAdapter(adapter);
           return v;
       }
   }


    class GridAdapter extends BaseListAdapter<GoodsInfoResult.DataEntity.InfoEntity.AttrEntity.ValueEntity> {
        private int clickPos = 0;
        private int groupPosition;
       public GridAdapter(Context context, List<GoodsInfoResult.DataEntity.InfoEntity.AttrEntity.ValueEntity> data,int groupPosition) {
           super(context, data);
           this.groupPosition = groupPosition;
       }

       @Override
       public View convert(final int i, View view, ViewGroup viewGroup, final GoodsInfoResult.DataEntity.InfoEntity.AttrEntity.ValueEntity bean) {
           View v = inflater.inflate(R.layout.item_size,null);
           TextView tv = v.findViewById(R.id.tv);
           tv.setText(bean.getName());
           if (clickPos == i){
               tv.setBackgroundResource(R.mipmap.bg_yes);
           }else {
               tv.setBackgroundResource(R.mipmap.bg_no);
           }
           v.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   clickPos = i;
                   notifyDataSetChanged();
                   ids.set(groupPosition,bean.getId() + "");
                   values.set(groupPosition,bean.getName());
                   getPrice();
               }
           });
           return v;
       }
   }

    private void getPrice() {
        progressBar.setVisibility(View.VISIBLE);
        NetWorkUtil.getGoodsPrice(StringUtil.listToStr(ids), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                progressBar.setVisibility(View.GONE);
                final PriceResult result = MyGson.getInstance().fromJson(data, PriceResult.class);
                if (null != result && result.getCode().equals("200")){
                    goodsPrice = result.getData().getGoods_price();
                    if (!StringUtil.isEmpty(goodsPrice)) {
                        price.setText(goodsPrice.substring(0, goodsPrice.indexOf(".")));
                        pricePoint.setText(goodsPrice.substring(goodsPrice.indexOf("."), goodsPrice.length()));
                    }
                }
            }
        });
    }


    public interface Callback {
        void onBuy(String id, String values, String price, String num);
        void onAdd(String id, String values, String price, String num);
    }

}
